package com.jochen.core.system

import com.artemis.Aspect
import com.artemis.systems.IteratingSystem
import com.jochen.core.components.MapObject
import com.jochen.core.components.Transform

class MapObjectSystem : IteratingSystem(Aspect.all(MapObject::class.java)) {

    override fun process(entityId: Int) {
        val obj = Mapper.mapObjects.get(entityId)
        val transform = Mapper.transforms.get(entityId)
        val moveStep = 2f * world.delta

        if (obj.moveXY) {
            handleYMovement(obj, transform, moveStep)
        } else {
            handleXMovement(obj, transform, moveStep)
        }
    }

    private fun handleYMovement(obj: MapObject, transform: Transform, moveStep: Float) {
        if (obj.isAdd) {
            transform.position.y += moveStep
            if (transform.position.y > obj.oldPos.y + obj.maxDistance) {
                obj.isAdd = false
            }
        } else {
            transform.position.y -= moveStep
            if (transform.position.y < obj.oldPos.y - obj.maxDistance) {
                obj.isAdd = true
            }
        }
    }

    private fun handleXMovement(obj: MapObject, transform: Transform, moveStep: Float) {
        if (obj.isAdd) {
            transform.position.x += moveStep
            if (transform.position.x > obj.oldPos.x + obj.maxDistance) {
                obj.isAdd = false
            }
        } else {
            transform.position.x -= moveStep
            if (transform.position.x < obj.oldPos.x - obj.maxDistance) {
                obj.isAdd = true
            }
        }
    }
}